/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.android.apps.mytracks.services.sensors.ant;

import static com.google.android.apps.mytracks.Constants.TAG;

import com.dsi.ant.AntMesg;
import com.dsi.ant.exception.AntInterfaceException;
import com.google.android.apps.mytracks.services.sensors.ant.AntPairer.PairingListener;

import android.content.Context;
import android.util.Log;

/**
 * An ANT sensor manager designed solely to handle pairing.  The algorithm used
 * is as follows:
 *
 * 1. Set up a channel for the provided sensor type
 * 2. Wait for a broadcast data from a sensor on that channel.
 * 3. Request the ID of the sensor which sent the broadcast data packet.
 * 4. Invoke {@link PairingListener#foundDevice} with the returned ID.
 *
 * @author Matthew Simmons
 */
class AntPairerSensorManager extends AbstractAntSensorManager {
  private final AntSensor sensor;
  private final PairingListener pairingListener;

  private boolean found;

  AntPairerSensorManager(Context context, AntSensor sensor, PairingListener pairingListener) {
    super(context);
    this.sensor = sensor;
    this.pairingListener = pairingListener;
    found = false;
  }

  @Override
  protected void handleOneMessage(byte channel, byte messageId, byte[] messageData)
      throws AntInterfaceException {
    if (channel != sensor.getChannelNumber()) {
      Log.d(TAG, "Ignoring message from channel " + channel);
      return;
    }

    switch (messageId) {
      case AntMesg.MESG_BROADCAST_DATA_ID:
        if (!found) {
          // TODO: Do we need to throttle this?
          getAntReceiver().ANTRequestMessage(channel, AntMesg.MESG_CHANNEL_ID_ID);
          Log.d(TAG, "Received broadcast data; requesting channel ID");
        }

      case AntMesg.MESG_CHANNEL_ID_ID:
        AntChannelIdMessage message = new AntChannelIdMessage(messageData);
        Log.i(TAG, "Found device id: " + message.getDeviceNumber());
        pairingListener.foundDevice(message.getDeviceNumber());
        found = true;
    }
  }

  @Override
  protected void setupAntSensorChannels() {
    setupAntSensorChannel(sensor.getChannelNumber(), WILDCARD, sensor.getDeviceType());
  }
}
